package cn.edu.scnu.semart.message.controller;


import cn.edu.scnu.semart.message.mapper.ChatConversationMapper;
import cn.edu.scnu.semart.model.chat.ChatConversation;
import cn.edu.scnu.semart.model.chat.CreateConversationDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
public class ConversationController {
    @Autowired
    private ChatConversationMapper chatConversationMapper;

    // 1. 查询当前用户所有相关会话
    @GetMapping("/chat/conversation/list")
    public IPage<ChatConversation> listConversations(@RequestParam Long userId,
                                                     @RequestParam(defaultValue = "1") int page,
                                                     @RequestParam(defaultValue = "20") int size) {
        Page<ChatConversation> pageObj = new Page<>(page, size);
        QueryWrapper<ChatConversation> wrapper = new QueryWrapper<>();
        wrapper.and(w -> w.eq("buyer_id", userId).or().eq("seller_id", userId));
        wrapper.orderByDesc("updated_at");
        return chatConversationMapper.selectPage(pageObj, wrapper);
    }

    // 2. 查询单个会话详情
    @GetMapping("/chat/conversation/{conversationId}")
    public ChatConversation getConversation(@PathVariable Long conversationId) {
        return chatConversationMapper.selectById(conversationId);
    }

    // 3. 创建会话（商品ID、买家ID、卖家ID）
    @PostMapping("/chat/conversation/create")
    @Transactional
    @ResponseBody
    public Long createConversation(@RequestBody CreateConversationDTO dto) {
        // 查找会话是否已存在
        QueryWrapper<ChatConversation> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", dto.getProductId())
                .eq("buyer_id", dto.getBuyerId())
                .eq("seller_id", dto.getSellerId());
        ChatConversation exist = chatConversationMapper.selectOne(wrapper);
        if (exist != null) {
            return exist.getConversationId();
        }
        // 不存在则新建
        ChatConversation conv = new ChatConversation();
        conv.setProductId(dto.getProductId());
        conv.setBuyerId(dto.getBuyerId());
        conv.setSellerId(dto.getSellerId());
        conv.setCreatedAt(new java.util.Date());
        conv.setUpdatedAt(new java.util.Date());
        chatConversationMapper.insert(conv);
        return conv.getConversationId();
    }
} 